package com.example.shirotest.realm;

import com.example.shirotest.entry.User;
import com.example.shirotest.service.UserService;
import com.example.shirotest.utils.MD5Util;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.security.NoSuchAlgorithmException;
import java.util.HashSet;
import java.util.Set;


public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    //角色权限设置
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        User user = (User) SecurityUtils.getSubject().getPrincipal();

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

/*        if("admin".equals(user.getRole())){
            info.addRole("admin");
            info.addStringPermission("*:*");
        }*/

            //添加角色
            String roleName = userService.getRoleByUid(user.getId());
            info.addRole(roleName);

            //添加权限
            Set<String> permission = userService.getPermsByUid(user.getId());
            info.setStringPermissions(permission);

        return info;
    }

    //登录账号密码验证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

        String username = token.getUsername();
        String password = "";
        if (token.getPassword() != null){
            password = new String(token.getPassword());
        }

        if(username.isEmpty() || password.isEmpty()){
            throw new UnknownAccountException("缺少账号或密码");
        }

        //查询数据库
        User user = userService.getUserByAccount(username);

        if(null==user){
            throw new UnknownAccountException("账号错误");
        }

        if(1==user.getLocked()){
            throw new LockedAccountException("账号被锁定");
        }

        try {
            if(!MD5Util.encrypt(password).equals(user.getPassword())){
                throw new IncorrectCredentialsException("登录密码不正确");
            }
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }

        return new SimpleAuthenticationInfo(user,user.getPassword(),getName());
    }
}
